package com.vtech.ont.base.impl;

import com.google.common.base.Strings;
import com.vtech.ont.base.OntModelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.jena.ontology.Individual;
import org.apache.jena.ontology.OntClass;
import org.apache.jena.ontology.OntModel;
import org.apache.jena.rdf.model.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 本体模型服务
 *
 * @author houzhiwei
 * @date 2017/6/29 11:25
 */
@Slf4j
@Service
public class OntModelServiceImpl implements OntModelService {

    @Override
    public OntModel toOntModel(Model model) {
        return (OntModel) ModelFactory.createOntologyModel().add(model);
    }

    @Override
    public List<Individual> createCoClsIndiBatch(String NS, List<String> indiNames, OntClass coCls, OntModel base) {
        List<Individual> indiLst = new ArrayList<Individual>();
        for (int i = 0, len = indiNames.size(); i < len; i++) {
            indiLst.add(base.createIndividual(NS + indiNames.get(i), coCls));
        }
        return indiLst;
    }

    @Override
    public List<Individual> addSamePropWithDefaultVal(List<Individual> indis, Property prop, Resource defaultVal) {
        for (Individual i : indis) {
            i.addProperty(prop, defaultVal);
        }
        return indis;
    }

    @Override
    public Resource createSubjectResource(String subURI, Model model) {
        Resource sub = (!Strings.isNullOrEmpty(subURI)) ? model.createResource(subURI) : (Resource) null;// 得到或创建
        return sub;
    }

    @Override
    public Property createPredicate(String predURI, Model model) {
        Property pred = (!Strings.isNullOrEmpty(predURI)) ? model.createProperty(predURI) : (Property) null;// 得到或创建
        return pred;
    }

    @Override
    public RDFNode createObjectRDFNode(String objURI, Model model) {
        RDFNode obj = (!Strings.isNullOrEmpty(objURI)) ? model.createResource(objURI) : (RDFNode) null;
        return obj;
    }

    @Override
    public List<Resource> getResourceFromModel(String term, OntModel model) {
        List<Resource> termRes = new ArrayList<>();
        List<String> list = getNsList(model);
        for (String ns : list) {
            RDFNode node = createObjectRDFNode(ns + term, model);
            if (model.containsResource(node)) {
                Resource resource = model.createResource(ns + term);
                termRes.add(resource);
            }
        }
        return termRes;
    }

    @Override
    public List<String> getNsList(OntModel model) {
        return model.listNameSpaces().toList();
    }
}
